
var express = require('express');
var router = express.Router();
const {Setting} = require('../../models')
console.log(Setting);
const {NotFoundError,success,failure} = require('../../utils/response')





// 根据id查找系统设置
router.get('/', async function(req, res, next) {
    try {
        const setting = await getSetting() 
        success(res,'查询系统设置列表成功',setting)
    } catch (error) {
        failure(res,error)
    }
    
});



// 更新系统设置
router.put('/',async function(req,res){
    try {
        const setting = await getSetting(req)
        const body = filterBody(req)
        await setting.update(body)
        success(res,'更新系统设置成功',{setting})
    } catch (error) {
        failure(res,error)
    }
    
})


function filterBody(req){
    return {
        name:req.body.name,
        icp:req.body.icp,
        copyright:req.body.copyright
    }
}

// 公共的查询方法，可以将未查询到信息的错误抛出
async function getSetting(){
    // 查找数据表中的第一条数据的方法
    const setting = await Setting.findOne()
    if(!setting){
        throw new NotFoundError(`系统设置未找到`)
    }
    return setting
}


module.exports = router;
